#include<stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include<string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
char arr[512];
char*res[32];
#define delim " "
int exitcode=0;
char* getname()
{
char*name=getenv("USER");
if(name==NULL)return NULL;
return name;



}
char*gethome()
{
char*home=getenv("HOME");
if(home==NULL)return NULL;
return home;




}
char* gethost()
{
char*hostname=getenv("HOSTNAME");
if(hostname==NULL)return NULL;
return hostname;
}
char* getpwd()
{
char*pwd=getenv("PWD");
if(pwd==NULL)return NULL;
char*p=pwd+strlen(pwd)-1;
while((*p)!='/')
 p--;

return p;


} 


void getlin()
{

printf("[%s@%s %s]$",getname(),gethost(),strlen(getpwd())==1 ? "/":getpwd()+1);
}

void getcommandstr(int size)
{

  fgets(arr,size,stdin);
  arr[strlen(arr)-1]='\0';
}

void Detachthestring()
{
res[0]=strtok(arr,delim);
int index=1;
while((res[index++]=strtok(NULL,delim)));

}
void dealcommand()
{
 int id=fork();
 if(id==0)
 {
  execvp(res[0],res);
  exit(errno);
 }
 int status=0;
 int rid=waitpid(id,&status,0);
 if(rid>0)
 {
   exitcode=WEXITSTATUS(status);
   if(exitcode!=0)
   printf("%s:%s:%d",res[0],strerror(exitcode),exitcode);
   exitcode=0;
 }
}
void cd()
{
char*path=res[1];
if(path==NULL)path=gethome();

chdir(path);
char cwd[1024];
char temp[1024];
getcwd(cwd,sizeof(cwd));
snprintf(temp, sizeof(temp),"PWD=%s",cwd);
putenv(temp);
}
int  Builtincommands()
{int yes=0;
 char*bulit=res[0]; 
 if(strcmp(bulit,"cd")==0)
 {
  yes=1;
  cd();
 }
else if(strcmp(bulit,"echo")==0&&strcmp(res[0],"$?")==0)
{
yes=1;
printf("%d",exitcode);




}
return yes;

}
int main()
{
  int quit=0;
  while(!quit)
  {
getlin();
getcommandstr(sizeof(arr));
Detachthestring();
int ret=Builtincommands();
if(ret)
continue;

dealcommand();

}}
